import { defineStore } from 'pinia'
import { login as loginApi, logout as logoutApi, getUserInfo } from '@/api/auth'

export const useAuthStore = defineStore('auth', {
  state: () => {
    const token = localStorage.getItem('token') || ''
    const userStr = localStorage.getItem('user')
    let user = null
    
    // 安全地解析用户数据
    if (userStr && userStr !== 'null' && userStr !== 'undefined') {
      try {
        user = JSON.parse(userStr)
      } catch (e) {
        console.warn('⚠️ 解析用户数据失败，已清除')
        localStorage.removeItem('user')
      }
    }
    
    return {
      token,
      user
    }
  },

  getters: {
    isAuthenticated: (state) => !!state.token,
    username: (state) => state.user?.username || ''
  },

  actions: {
    /**
     * 设置登录信息
     */
    setAuth(token, user) {
      console.log('🔧 setAuth 调用:', { token: token ? `${token.substring(0, 20)}...` : 'null', user })
      this.token = token
      this.user = user
      localStorage.setItem('token', token)
      localStorage.setItem('user', JSON.stringify(user))
      console.log('✅ 已保存认证信息到store')
      console.log('🔍 Store更新后:', { token: this.token ? '有值' : '无值', isAuth: this.isAuthenticated })
    },

    /**
     * 设置用户信息
     */
    setUser(user) {
      this.user = user
      localStorage.setItem('user', JSON.stringify(user))
    },

    /**
     * 清除用户信息
     */
    clearUser() {
      this.token = ''
      this.user = null
      localStorage.removeItem('token')
      localStorage.removeItem('user')
    },

    /**
     * 检查认证状态
     */
    async checkAuth() {
      if (!this.token) {
        return false
      }

      try {
        console.log('🔍 检查登录状态...')
        const res = await getUserInfo()
        this.user = res.data
        localStorage.setItem('user', JSON.stringify(this.user))
        console.log('✅ 登录状态有效')
        return true
      } catch (error) {
        console.warn('⚠️  登录状态已失效')
        this.clearUser()
        return false
      }
    }
  }
})

